﻿class Timer
{
    public delegate void OnTickEvent(object sender);

    /// <summary>
    /// Occurs after the timers interval has elapsed.
    /// </summary>
    public event OnTickEvent OnTick;

    private int interval;
    private int lastTick;
    private bool enabled = true;

    /// <summary>
    /// Interval of the timer in milliseconds.
    /// </summary>
    public int Interval
    {
        get { return interval; }
        set { interval = value; }
    }

    /// <summary>
    /// Enable the timer.
    /// </summary>
    public bool Enabled
    {
        get { return enabled; }
        set 
        { 
            enabled = value;
            if (enabled)
                lastTick = System.Environment.TickCount;
        }
    }

    /// <summary>
    /// Creates new timer.
    /// </summary>
    /// <param name="timerInterval">Interval in milliseconds.</param>
    public Timer(int timerInterval)
    {
        interval = timerInterval;
        lastTick = System.Environment.TickCount;
    }

    /// <summary>
    /// Updates the timer. Call this in loop passing current Environment.TickCount.
    /// </summary>
    /// <param name="milliseconds">Current TickCount.</param>
    public void UpdateTimer(int milliseconds)
    {
        int thisTick;

        if (enabled)
        {
            thisTick = milliseconds - lastTick;

            if (thisTick > interval)
            {
                lastTick = milliseconds;
                OnTick(this);
            }
        }
    }

}